package com.zxy.ziems.server.storage;

import cn.hutool.core.collection.CollectionUtil;
import com.zxy.btp.common.util.JsonUtils;
import com.zxy.btp.redis.utils.RedisUtil;
import com.zxy.ziems.common.mqtt.BaseListMqttConsumer;
import com.zxy.ziems.common.mqtt.annotation.MqttTopic;
import com.zxy.ziems.common.mqtt.pojo.Pattern;
import com.zxy.ziems.common.pojo.MeasureDataBean;
import com.zxy.ziems.server.alarm.enums.GasAlarmStatusEnum;
import com.zxy.ziems.server.alarm.service.AlarmRecordService;
import com.zxy.ziems.server.device.pojo.enums.DeviceAlarmStatus;
import com.zxy.ziems.server.storage.service.MeasureDataStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

/**
 * 可燃气体报警数据存储监听
 *
 * @author 10546533
 * @create 2024-05-10 10:23
 */
@Slf4j
@Component
@MqttTopic(
        topic = "${zxy.topic.gas-alarm-data}",
        patten = Pattern.SHARE,
        group = "gasAlarmDataStorage",
        qos = 1
)
public class GasAlarmDataStorageListener extends BaseListMqttConsumer<MeasureDataBean> {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doProcessMessage(String topic, List<MeasureDataBean> list, LocalDateTime sendTime) {
        List<MeasureDataBean> gasAlarms = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (MeasureDataBean measureDataBean : list) {
                StringJoiner cacheKey = new StringJoiner(":");
                cacheKey.add("GAS_ALRAM");
                cacheKey.add(measureDataBean.getDeviceId());
                cacheKey.add(measureDataBean.getDataTypeId());
                cacheKey.add(measureDataBean.getMeasureValue());
                if (redisUtil.hasKey(cacheKey.toString())){
                    gasAlarms.add(measureDataBean);
                    redisUtil.incr(cacheKey.toString(),1L);
                }else {
                    redisUtil.set(cacheKey.toString(), 1, 5L, TimeUnit.SECONDS);
                }
            }
            if (CollectionUtil.isNotEmpty(gasAlarms)) {
                log.info("[MQTT]接收可燃气体告警数据：" + JsonUtils.toJSONString(gasAlarms));
                alarmRecordService.storageAlarmByAlamRule(list);
            }
        }
    }

    private AlarmRecordService alarmRecordService;

    @Autowired
    @Lazy
    public void setStorageService(AlarmRecordService alarmRecordService) {
        this.alarmRecordService = alarmRecordService;
    }
}
